import os
import shutil
import Image

class ImageStorage():
    root_dir = None
    max_dirs = 10000
    allowed_geometries = ((100, 100), (400, 400))
    
    def __init__(self, root_dir='./data/images'):
        self.root_dir = root_dir
        
    def save(self, file, image_id, image_name):
        file_path = self.file_path(image_id, image_name)
        os.makedirs(self.dir_path(image_id, image_name))
        permanent_file = open(file_path, 'w+b')
        shutil.copyfileobj(file, permanent_file)
        file.close()
        permanent_file.close()
    
    def delete(self, image_id, image_name):
        shutil.rmtree(self.dir_path(image_id, image_name), ignore_errors=True)
    
    def file_path(self, image_id, image_name):
        f_name = '%s_%s' % (image_id, image_name)
        return os.path.join(self.dir_path(image_id, image_name), f_name)

    def get_thumbnail_path(self, image_id, image_name, width=None, height=None, format=None):
        f_name = '%s_%s' % (image_id, image_name)
        dir_path = self.dir_path(image_id, image_name)
        size = (width, height)
        if width==None or height==None or not size in self.allowed_geometries:
            return os.path.join(dir_path, f_name)
        t_file_name = self.__format_thubnail_file_name(f_name, width, height, format)
        t_path = os.path.join(dir_path, t_file_name)
        if not os.path.exists(t_path):
            im = Image.open(os.path.join(dir_path, f_name))
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(t_path, format=format, quality=95)
        return t_path    
        
    def __format_thubnail_file_name(self, image_file_name, width, height, format):
        return 'T_w%s_h%s_f%s_%s'% (width, height, format if format != None else 'ORIGINAL', image_file_name)
        
    def dir_path(self, image_id, image_name):
        f_name = '%s_%s' % (image_id, image_name)
        return os.path.join(self.root_dir, str(image_id / self.max_dirs), f_name)
            
        